package com.hx.dc.controllor;

import com.hx.dc.entity.CommoDity;
import com.hx.dc.entity.Picture;
import com.hx.dc.util.FileUploadUtil;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lenovo on 2019/3/1.
 */

@Controller
@RequestMapping("/upload")
public class PictureAction {

    @Resource
    ServletContext application;

    @RequestMapping(value="/save")
    @ResponseBody
    public Object save(Picture picture){

     System.out.println("save11111111111111111111111111111111111111111:"+picture);
       Map<String,String> returnMap = new HashMap<>();
        System.out.print("1111111111"+picture.getFiles());
        MultipartFile[] files=picture.getFiles();
        for(MultipartFile file:files){
            if(file.isEmpty()){
                System.out.println("文件为空");
                returnMap.put("msg","0");
            }else{
                System.out.println("真实路径："+application.getRealPath("/"));
                System.out.println("文件不为空！");
                System.out.println("格式:" + file.getContentType());
                System.out.println("原名:" + file.getOriginalFilename());
                System.out.println("大小:" + file.getSize());
                System.out.println("根目录："+System.getProperty("catalina.home"));
                try {
                    String newName = FileUploadUtil.createNewName(file);

                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(application.getRealPath("/")+"upload/"+newName));
                    returnMap.put("msg",newName);
                } catch (IOException e) {
                    returnMap.put("msg","0");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return returnMap;
    }

}
